<?php
namespace app\common\model;

use app\common\model\UserSiteAccess;
use think\facade\Cookie;
use think\facade\Request;
use think\facade\Session;
use think\facade\Validate;
use think\Model;
use think\model\concern\SoftDelete;

class UserMain extends Model
{
    use SoftDelete;
    protected $error             = false;
    protected $pk                = 'uid';
    protected $deleteTime        = 'delete_time';
    protected $defaultSoftDelete = 0;
    protected $type              = [
        'register_time' => 'timestamp',
        'last_time'     => 'timestamp',
		'vip_expire_time' => 'timestamp'
    ];

    public function getError()
    {
        return $this->error;
    }

    public static function onBeforeInsert($data)
    {
        $data->register_time = Request::time();
        $data->register_ip   = Request::ip();
        $validate            = Validate::rule([
            'username' => 'require|max:30|unique:user_main,username',
            'email'    => 'email|unique:user_main,email',
            'mobile'   => 'mobile|unique:user_main,mobile',
        ])
            ->message([
                'username.require' => '用户名必填',
                'username.max'     => '用户名最大长度30字符',
                'username.unique'  => '用户名已存在',
                'email.email'      => '邮箱输入错误',
                'email.unique'     => '邮箱已存在',
                'mobile.mobile'    => '手机号输入错误',
                'mobile.unique'    => '手机号已存在',
            ]);

        if (!$validate->check($data->toArray())) {
            $data->error = $validate->getError();
            return false;
        }
        if (Validate::isMobile($data->username)) {
            $data->error = '用户名不能是手机号';
            return false;
        }
        if (Validate::isEmail($data->username)) {
            $data->error = '用户名不能是邮箱';
            return false;
        }
    }

    public static function onBeforeUpdate($data)
    {
        $validate = Validate::rule([
            'username' => 'require|max:30|unique:user_main,username',
            'email'    => 'email|unique:user_main,email',
            'mobile'   => 'mobile|unique:user_main,mobile',
        ])
            ->message([
                'username.require' => '用户名必填',
                'username.max'     => '用户名最大长度30字符',
                'username.unique'  => '用户名已存在',
                'email.email'      => '邮箱输入错误',
                'email.unique'     => '邮箱已存在',
                'mobile.mobile'    => '手机号输入错误',
                'mobile.unique'    => '手机号已存在',
            ]);

        if (!$validate->check($data->toArray())) {
            $data->error = $validate->getError();
            return false;
        }
        if (Validate::isMobile($data->username)) {
            $data->error = '用户名不能是手机号';
            return false;
        }
        if (Validate::isEmail($data->username)) {
            $data->error = '用户名不能是邮箱';
            return false;
        }
    }

    protected function setPasswordAttr($value)
    {
        return password_hash(md5($value), PASSWORD_DEFAULT);
    }

    public function getParseMaxTimesTextAttr($value, $data)
    {
        if ($data['parse_max_times'] < 0) {
            return '无权限';
        } else if ($data['parse_max_times'] == 0) {
            return '无限制';
        } else {
            return $data['parse_max_times'] . '次';
        }
    }

    public function getTypeTextAttr($value, $data)
    {
        switch ($data['type']) {
            case 'system':
                return '管理员';
                break;
            case 'proxy':
                return '代理';
                break;
            case 'member':
                return '会员';
                break;

            default:
                return '未知';
                break;
        }
    }
	
	public function getVipTypeTextAttr($value,$data){
		switch ($data['vip_type']) {
		    case 0:
		        return '体验卡用户';
		        break;
			case 2:
				return '月卡';
			case 3:
				return '年卡';
		    case 1:
		        return '周卡';
		        break;
		    case -1:
		        return '终身';
		        break;
		    default:
		        return '非vip用户';
		        break;
		}
	}

    public function getStatusTextAttr($value, $data)
    {
        switch ($data['status']) {
            case 0:
                return '待审核';
                break;
            case 1:
                return '正常';
                break;
            case -1:
                return '禁用';
                break;

            default:
                return '未知';
                break;
        }
    }

    public function siteAccess()
    {
        return $this->hasMany('UserSiteAccess', 'uid', 'uid');
    }

    public function update_access_time()
    {
        $time_now = Request::time();
        foreach (UserSiteAccess::where([['uid', '=', $this->getAttr('uid')], ['out_time', '>', '0'], ['out_time', '<=', '999999999']])->select() as $access) {
            if ($access->getData('out_time') > 0 && $access->getData('out_time') <= 999999999) {
                UserSiteAccess::where('id', '=', $access['id'])->update([
                    'out_time' => $time_now + ($access->getData('out_time') * 3600),
                ]);
            }
        }
        foreach (UserDownloadTimes::where([['uid', '=', $this->getAttr('uid')], ['out_time', '>', '999999999'], ['out_time', '<=', $time_now]])->select() as $times) {
            UserDownloadTimes::where('id', '=', $times['id'])->update([
                'status' => 0,
            ]);
        }
    }

    public function login()
    {
        global $_G;
        if (empty($this->getAttr('uid'))) {
            return false;
        }
        $time_now        = Request::time();
        $this->last_time = $time_now;
        $this->last_ip   = Request::ip();
        $this->save();
        $this->update_access_time();
        $login = [
            'uid'       => $this->getAttr('uid'),
            'password'  => md5($this->getAttr('password')),
            'last_time' => $this->getData('last_time'),
            'last_ip'   => $this->getData('last_ip'),
        ];
        Session::set('login', $login);
        Cookie::set('login', authcode(json_encode($login), 'ENCODE'), 2592000);
        $_G['uid']  = $this->getAttr('uid');
        $_G['user'] = $this;
        return true;
    }

    public function logout()
    {
        global $_G;
        Session::delete('login');
        Cookie::delete('login');
        $_G['uid']  = 0;
        $_G['user'] = [];
        return true;

    }
}
